package org.quartz.impl.jdbcjobstore;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UpdateLockRowSemaphore extends DBSemaphore {

	public static final String UPDATE_FOR_LOCK = "UPDATE " + TABLE_PREFIX_SUBST + TABLE_LOCKS + " SET " + COL_LOCK_NAME
			+ " = " + COL_LOCK_NAME + " WHERE " + COL_LOCK_NAME + " = ? ";

	public UpdateLockRowSemaphore() {
		super(DEFAULT_TABLE_PREFIX, null, UPDATE_FOR_LOCK);
	}

	protected void executeSQL(Connection conn, String lockName, String expandedSQL) throws LockException {
		PreparedStatement ps = null;

		try {
			ps = conn.prepareStatement(expandedSQL);
			ps.setString(1, lockName);

			if (getLog().isDebugEnabled()) {
				getLog().debug("Lock '" + lockName + "' is being obtained: " + Thread.currentThread().getName());
			}

			int numUpdate = ps.executeUpdate();

			if (numUpdate < 1) {
				throw new SQLException(Util.rtp(
						"No row exists in table " + TABLE_PREFIX_SUBST + TABLE_LOCKS + " for lock named: " + lockName,
						getTablePrefix()));
			}
		} catch (SQLException sqle) {
			if (getLog().isDebugEnabled()) {
				getLog().debug("Lock '" + lockName + "' was not obtained by: " + Thread.currentThread().getName());
			}

			throw new LockException("Failure obtaining db row lock: " + sqle.getMessage(), sqle);
		} finally {
			if (ps != null) {
				try {
					ps.close();
				} catch (Exception ignore) {
				}
			}
		}
	}

	protected String getUpdateLockRowSQL() {
		return getSQL();
	}

	public void setUpdateLockRowSQL(String updateLockRowSQL) {
		setSQL(updateLockRowSQL);
	}
}
